# -*- coding: utf-8 -*-
# @Time : 2020/4/2 1:07
# @Author : hlikex
# @File : Reply.py
from time import sleep
import random
import logging
import logger
import re

class Reply:
    def __init__(self,driver):
        logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.logger = logging.getLogger(__name__)
        self.driver = driver
        f = open("Reply.txt","r",encoding='UTF-8')
        self.R_massage = f.read()
        f.close()
        self.Spam()

    def RetrieveEmail(self):
        self.driver.switch_to.default_content()
        SID = re.findall(r"sid=(.*?)&",self.driver.current_url)[0] # 获取SID
        # 搜索指定未读邮件
        self.driver.get("https://mail.qq.com/cgi-bin/frame_html?t=frame_html&sid={}&url=/cgi-bin/mail_list?topmails=0%26s=search%26sender={}%26page=0%26folderid=all%26flagnew=new".format(SID,"xiaohuimc@hotmail.com"))
        # 切换框架
        self.driver.switch_to.frame("mainFrame")
        num =None
        sleep(0.5)
        if self.isElementExist('xpath','//*[@id="qqmail_mailcontainer"]/div[1]/span/b[3]'):
            num = self.driver.find_element_by_xpath('//*[@id="qqmail_mailcontainer"]/div[1]/span/b[3]').text
            sleep(0.5)
        elif self.isElementExist("xpath",'//*[@id="qqmail_mailcontainer"]/div[2]/span/b[3]'):
            num = self.driver.find_element_by_xpath('//*[@id="qqmail_mailcontainer"]/div[2]/span/b[3]').text

        self.logger.info("有{}封未读邮件！！！".format(num))
        if self.isElementExist("id", "div_showtoday"):
            # self.driver.find_element_by_id("div_showtoday").click()
            self.driver.find_element_by_xpath('//*[@id="div_showtoday"]/table[1]').click()
            self.Reply()
            sleep(5)
            # self.RetrieveEmail()
        else:
            self.logger.info("正在退出QQ邮箱")
            self.driver.quit()
            return None
        if int(num) > 1:
            self.RetrieveEmail()
        self.logger.info("正在退出QQ邮箱")
        self.driver.quit()
        return None

    # 随机生成字符串
    def Unicode(self):
        str = ""
        for i in range(5):
            val = random.randint(0x4e00, 0x9fbf)
            str = str + chr(val)
        return str

    def isElementExist(self, by, value):
        try:
            self.driver.find_element(by=by, value=value)
            return True
        except Exception as e:
            return False

    def Spam(self):
        self.logger.info("正在检测垃圾邮件")
        while True:
            try:
                SpamNum = self.driver.find_element_by_xpath('//*[@id="folder_6"]/b[2]').text
                # 整转换
                SpamNum = int(str(SpamNum).strip("(").strip(")"))
            except:
                SpamNum = 0
            if SpamNum != 0:
                self.driver.find_element_by_id("folder_6").click()
                self.driver.switch_to.frame("mainFrame")
                sleep(1)
                self.driver.find_element_by_xpath('//*[@id="frm"]/div[6]/div/a[1]').click()
                sleep(1)
                self.driver.find_element_by_xpath('//*[@id="frm"]/div[7]/div[2]/a[4]').click()
                self.driver.switch_to.default_content()
            elif SpamNum == 0:
                break

    # 添加回复内容
    def Reply(self):
        if self.isElementExist("xpath",'//*[@id="source"]'):
            sleep(1)
            self.driver.find_element_by_xpath('//*[@id="source"]').clear()
        elif self.isElementExist("css_selector","[class='graytext qm_txt']"):
            sleep(1)
            self.driver.find_element_by_css_selector("[class='graytext qm_txt']").clear()

        self.driver.switch_to.default_content()
        self.driver.switch_to.__class__("qmEditorIfrmEditArea")
        massage = "    \n"+self.Unicode() +"[{}]".format(self.R_massage) +self.Unicode()
        self.driver.find_element_by_xpath('/html/body').send_keys(massage)
        sleep(0.5)
        self.driver.switch_to.frame('mainFrame')
        sleep(1)
        self.driver.find_element_by_id("sendbtn").click()
        self.driver.switch_to.default_content()

        # 输出错误提示
        if self.isElementExist("class","errmsg"):
            flag = self.driver.find_element_by_class_name("errmsg").get_attribute()
            logger.error(flag)
        self.logger.info("回复成功！！！")
        sleep(2)

